package hazesoft.Collection;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.text.DateFormat;
import java.util.Date;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import com.pushlink.android.PushLink;
import com.pushlink.android.strategy.FriendlyPopUpStrategy;
import com.pushlink.android.strategy.StatusBarStrategy;
import com.pushlink.android.strategy.StrategyEnum;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.*;
import android.widget.Toast;



public class African_Honey_CollectionActivity extends Activity {
    
	public void MessageBox(String message){
	    Toast.makeText(this,message,Toast.LENGTH_LONG).show();
	}
	
	public String GetPref(String Key)
	{
		return this.getSharedPreferences("AHB",MODE_PRIVATE).getString(Key, null);
	}
	
	public void SavePref(String Key, String Value)
	{
		Editor e = this.getSharedPreferences("AHB",MODE_PRIVATE).edit();
		e.putString(Key, Value);
		e.commit();
		
	}
	
	public void CheckMessages()
	{
		
		
		
		NotificationManager mManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		Intent notificationIntent = new Intent(this, African_Honey_CollectionActivity.class);
		PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

		
		
		
		String Messages = "";
		try
		{
		HttpClient httpclient = new DefaultHttpClient();
		HttpResponse response = httpclient.execute(new HttpGet(GetPref("MESSAGE_ADDRESS") + "?Type=Check&PID=" + GetPref("PHONE_ID")));
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		response.getEntity().writeTo(out);
		Messages = out.toString();
		String[] Items;
		String sMessage = "";
			if(Messages != "")
			{
				Items = Messages.split("\\$");
				for(int x = 0; x < Items.length; x++)
				{
					int icon = R.drawable.icon;       // icon from resources
					CharSequence tickerText = "AHB Collection";              // ticker-text
					long when = System.currentTimeMillis();         // notification time
					Context context = getApplicationContext();   // application Context
					CharSequence contentTitle = "AHB Collection";  // message title
					CharSequence contentText = "New Message";      // message text
					
					sMessage = Items[x];
					String Body = sMessage.split("\\|")[0];
					String From = sMessage.split("\\|")[1];
					contentTitle = "New AHB Message From " + From;
					contentText = Body;
					// the next two lines initialize the Notification, using the configurations above
					Notification notification = new Notification(icon, tickerText, when);
					notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
					notification.defaults |= Notification.DEFAULT_SOUND;
					MessageBox("You have a new message");
					if(Body == "WIPE" && From == "CMD")
					{
						String[] Files = fileList();
						for(int y = 0; x < Files.length; x++)
						{
							deleteFile(Files[y]);
						}
					}
					else
					{
						FileOutputStream outs = openFileOutput(DateFormat.getDateInstance().format(new Date()) + ".msg", Context.MODE_WORLD_READABLE);
						OutputStreamWriter fsout = new OutputStreamWriter(outs);
						fsout.write(From + "\n");
						fsout.write(Body);
						fsout.close();
						outs.close();
						mManager.notify(x, notification);
					}
				}
				
			}
		}
		catch(Exception ex)
		{
			
		}
	}
	
	
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       if(GetPref("FIRST") != "FALSE")
        {
    	    findViewById(R.id.btnCollect).setEnabled(false);
    	    findViewById(R.id.btnUpload).setEnabled(false);
       	    //findViewById(R.id.edtError).setVisibility())
    	    Intent i = new Intent(African_Honey_CollectionActivity.this, Collection_Setup.class);
			startActivity(i);        	
        }
        
        CheckMessages();
        
        
        
        
        PushLink.start(this, R.drawable.icon, 10, "c0ef67cc473fc39d", true);
        
        PushLink.setCurrentStrategy(StrategyEnum.FRIENDLY_POPUP);
        FriendlyPopUpStrategy friendlyPopUpStrategy = (FriendlyPopUpStrategy)PushLink.getCurrentStrategy();
        friendlyPopUpStrategy.setPopUpMessage("There is a new version of the AHB Collection software");
        friendlyPopUpStrategy.setUpdateButton("Update Now");
        friendlyPopUpStrategy.setNotNowButton("No, Thanks");
        friendlyPopUpStrategy.setReminderTimeInSeconds(60 * 60); //1 hour
        
        PushLink.setCurrentPopUpTarget(this);
        
        //

        	findViewById(R.id.btnCollect).setOnClickListener(btnCollect_OnClick);
        	findViewById(R.id.btnUpload).setOnClickListener(btnUpload_OnClick);
        	findViewById(R.id.btnSettings).setOnClickListener(btnSettings_OnClick);
        	
     
        //
        
    }
    
   
    
    public View.OnClickListener btnCollect_OnClick = new View.OnClickListener() {
		
		public void onClick(View v) {
			Intent i = new Intent(African_Honey_CollectionActivity.this, Collection_Collect_Activity.class);
			 startActivity(i);
		}
	};
	
	  public View.OnClickListener btnUpload_OnClick = new View.OnClickListener() {
			
			public void onClick(View v) {
				Intent i = new Intent(African_Honey_CollectionActivity.this, Collection_Upload.class);
				 startActivity(i);
			}
		};
		
		public View.OnClickListener btnSettings_OnClick = new View.OnClickListener() {
			
			public void onClick(View arg0) {
				Intent i = new Intent(African_Honey_CollectionActivity.this, CollectionSettingsActivity.class);
				 startActivity(i);
				
			}
		};
		

	
	
}